package cn.stylefeng.guns.modular.agv.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.agv.entity.CollectionLocationVo;
import cn.stylefeng.guns.modular.agv.entity.HikAgvRoadWay;
import cn.stylefeng.guns.modular.agv.entity.RoadWayListRsVo;
import cn.stylefeng.guns.modular.agv.mapper.HikAgvRoadWayMapper;
import cn.stylefeng.guns.modular.agv.mapper.HikAgvTaskMapper;
import cn.stylefeng.guns.modular.agv.model.params.HikAgvRoadWayParam;
import cn.stylefeng.guns.modular.agv.model.params.RoadWayListParam;
import cn.stylefeng.guns.modular.agv.model.params.XlbClientParamVo;
import cn.stylefeng.guns.modular.agv.model.result.HikAgvRoadWayResult;
import cn.stylefeng.guns.modular.agv.model.result.RoadWayRunCntVo;
import cn.stylefeng.guns.modular.agv.model.result.XlbClientData;
import cn.stylefeng.guns.modular.agv.model.result.XlbClientRS;
import  cn.stylefeng.guns.modular.agv.service.HikAgvRoadWayService;
import cn.stylefeng.guns.modular.agv.util.StorageDataVo;
import cn.stylefeng.guns.modular.agv.util.StorageRsVo;
import cn.stylefeng.guns.modular.agv.util.TustApiUtils;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.BasicXlbOauth2tokenService;
import cn.stylefeng.guns.modular.hx.storage.entity.HxCollectionLocation;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxCollectionLocationParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxCollectionLocationResult;
import cn.stylefeng.guns.modular.hx.storage.service.HxCollectionLocationService;
import cn.stylefeng.guns.modular.transport.mapper.TransportMsgMapper;
import cn.stylefeng.guns.modular.transport.model.params.TransportMsgParam;
import cn.stylefeng.guns.modular.transport.model.result.TransportMsgResult;
import cn.stylefeng.guns.modular.transport.utils.XlbApiUtils;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 海康小车巷道情况 服务实现类
 * </p>
 *
 * @author zhangzh
 * @since 2024-06-06
 */
@Service
public class HikAgvRoadWayServiceImpl extends ServiceImpl<HikAgvRoadWayMapper, HikAgvRoadWay> implements HikAgvRoadWayService {

    @Resource
    private HikAgvTaskMapper hikAgvTaskMapper;

    @Resource
    private TransportMsgMapper transportMsgMapper;

    @Resource
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    @Resource
    private HxCollectionLocationService hxCollectionLocationService;

    @Value("${hxl.api.url}")
    private String hxlApiUrl;

    @Value("${tusk.baseUrl}")
    private String tuskBaseUrl;

    @Override
    public void add(HikAgvRoadWayParam param){
        HikAgvRoadWay entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(HikAgvRoadWayParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(HikAgvRoadWayParam param){
        HikAgvRoadWay oldEntity = getOldEntity(param);
        HikAgvRoadWay newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public HikAgvRoadWayResult findBySpec(HikAgvRoadWayParam param){
        return null;
    }

    @Override
    public List<HikAgvRoadWayResult> findListBySpec(HikAgvRoadWayParam param){
        return this.baseMapper.customList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(HikAgvRoadWayParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public List<Map<String,RoadWayListRsVo>> RoadWayList(RoadWayListParam param) {
        List<Map<String,RoadWayListRsVo>> rs = new ArrayList();
        Map<String,RoadWayListRsVo> rsMap = new HashMap<>();
        RoadWayListRsVo rsVo = null;
        HikAgvRoadWayParam q = new HikAgvRoadWayParam();
        if(ToolUtil.isNotEmpty(param.getPlateNumber())){
            q.setPlateNumber(param.getPlateNumber());
        }
        if(ToolUtil.isNotEmpty(param.getClientName())){
            q.setClientName(param.getClientName());
        }
        if(ToolUtil.isNotEmpty(param.getOrderBy())){
            q.setOrderBy(param.getOrderBy());
        }

        //获取新零帮巷道信息情况
        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setGsnumber("66666");
        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
        XlbClientParamVo apiParam = new XlbClientParamVo();
        Map<String,XlbClientData> clientInfoMap = new HashMap<>();
        try{

            XlbClientRS clientInfo = XlbApiUtils.getClientInfo(this.hxlApiUrl, apiParam, oauth2tokenResult.getOauth2TokenXlb());
            if(clientInfo != null && clientInfo.getCode() == 0 && clientInfo.getData() != null && clientInfo.getData().size() > 0){
                for(XlbClientData obj : clientInfo.getData()){
                    clientInfoMap.put(obj.getChannel_name(),obj);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        // 获取正在执行的任务数
        List<RoadWayRunCntVo> taskRunCntList = hikAgvTaskMapper.getTaskRunCnt();
        Map<String,Integer> taskRunCntMap = new HashMap<>();
        for(RoadWayRunCntVo obj : taskRunCntList){
            taskRunCntMap.put(obj.getRoadWayCode(),obj.getRunCnt());
        }
        List<HikAgvRoadWayResult> hikAgvRoadWayResults = this.baseMapper.customList(q);
        int n = 0;
        int row = 1;
        for(HikAgvRoadWayResult obj : hikAgvRoadWayResults){
            n++;
            String channelName = StringUtils.leftPad(obj.getRoadWayCode(),3,"0")+"巷道";
            rsVo = new RoadWayListRsVo();
            rsVo.setRoadWayCode(channelName);
            rsVo.setAllNum(obj.getAllNum());
            rsVo.setSeq(obj.getSeq());
            rsVo.setPlateNumber(obj.getPlateNumber());
            rsVo.setTrainSeq(obj.getTrainSeq());
            rsVo.setTrainRoadWaySeq(obj.getTrainRoadWaySeq());
            rsVo.setClientId(obj.getClientId());
            rsVo.setClientName(obj.getClientName());
            rsVo.setDockPlat(obj.getDockPlat());
            rsVo.setFlag(obj.getFlag());
            //处理巷道位置 已放托
            Integer seq = Integer.valueOf(rsVo.getSeq());
            rsVo.setHuoCnt(seq);

            //处理巷道位置 已下任务
            Integer roadWayRunCnt = taskRunCntMap.get(obj.getRoadWayCode());
            Integer zhanCnt = 0;
            if(roadWayRunCnt != null){
                zhanCnt = roadWayRunCnt;
                if(rsVo.getAllNum() - seq < roadWayRunCnt){
                    zhanCnt = rsVo.getAllNum() - seq;
                }
            }else{
                roadWayRunCnt = 0;
            }
            rsVo.setZhanCnt(zhanCnt);


            if(clientInfoMap.get(channelName) != null){
                //已推单数量
                int ytd = clientInfoMap.get(channelName).getExpect_pallet_num() - (roadWayRunCnt + seq);
                //已集货数量
                int yjh = clientInfoMap.get(channelName).getDistributed_pallet_num() - (roadWayRunCnt + seq);
                if(yjh > 0){
                    rsVo.setJiCnt(yjh);
                }
                if(ytd > 0 && yjh > 0 && ytd > yjh ){
                    rsVo.setJianCnt(ytd - yjh);
                }
                rsVo.setLatestDistributeTime(clientInfoMap.get(channelName).getLatest_distribute_time());
            }
            rsVo.setKongCnt(rsVo.getAllNum() - seq - zhanCnt - rsVo.getJianCnt() - rsVo.getJiCnt());
            //处理巷道位置 超托
            Integer chao = roadWayRunCnt + seq  - rsVo.getAllNum();
            rsVo.setChaoCnt(chao);

            rsMap.put("C"+n,rsVo);
            if(n >=7 || row == hikAgvRoadWayResults.size()){
                rs.add(rsMap);
                rsMap = new HashMap<>();
                n = 0;
            }
            row++;
        }
        return rs;
    }

    @Override
    public List<Map<String, RoadWayListRsVo>> tuskRoadWayList(RoadWayListParam param) {
        List<Map<String,RoadWayListRsVo>> rs = new ArrayList();
        Map<String,RoadWayListRsVo> rsMap = new HashMap<>();

        HxCollectionLocationParam q1 = new HxCollectionLocationParam();
        q1.setDeptId(1732227776252375042L);
        q1.setOperateId(44L);
        List<HxCollectionLocationResult> listBySpecs = hxCollectionLocationService.findListBySpec(q1);
        Map<String, String> unitMap = new HashMap<>();
        for(HxCollectionLocationResult obj : listBySpecs){
            if(unitMap.get(obj.getStockPort()) == null){
                if(ToolUtil.isNotEmpty(obj.getGetUnit())){
                    unitMap.put("H"+ StringUtils.leftPad(obj.getStockPort(),3,"0"),obj.getGetUnit());
                }
            }
        }

        RoadWayListRsVo rsVo;
        StorageRsVo mapStorage ;
        if(ToolUtil.isNotEmpty(param.getPlateNumber())){
            mapStorage = TustApiUtils.getMapStorageByRoadway(tuskBaseUrl,param.getPlateNumber());
        }else{
            mapStorage = TustApiUtils.getMapStorage(tuskBaseUrl);
        }
        if(mapStorage!=null && mapStorage.getCode() == 200){
            int n = 0;
            int row = 1;
            for(StorageDataVo obj : mapStorage.getData()){
                n++;
                rsVo = new RoadWayListRsVo();
                rsVo.setRoadWayCode(obj.getAreaName());
                rsVo.setAllNum(obj.getAllNum());
                rsVo.setKongCnt(obj.getEmptyNum());
                rsVo.setHuoCnt(obj.getFullNum());
                rsVo.setZhanCnt(obj.getLockNum());
                rsVo.setClientName(unitMap.get(obj.getAreaName()));
                rsMap.put("C"+n,rsVo);
                if(n >=7 || row == mapStorage.getData().size()){
                    rs.add(rsMap);
                    rsMap = new HashMap<>();
                    n = 0;
                }
                row++;
            }
        }
        return rs;
    }

    @Override
    public List<RoadWayListRsVo> reestRoadWayList(RoadWayListParam param) {
        List<RoadWayListRsVo> rs = new ArrayList();
        RoadWayListRsVo rsVo;
        HikAgvRoadWayParam q = new HikAgvRoadWayParam();
        if(ToolUtil.isNotEmpty(param.getPlateNumber())){
            q.setPlateNumber(param.getPlateNumber());
        }
        if(ToolUtil.isNotEmpty(param.getClientName())){
            q.setClientName(param.getClientName());
        }
        if(ToolUtil.isNotEmpty(param.getOrderBy())){
            q.setOrderBy(param.getOrderBy());
        }
        if(ToolUtil.isNotEmpty(param.getKeyword())){
            q.setKeyword(param.getKeyword());
        }

        // 获取正在执行的任务数
        List<RoadWayRunCntVo> taskRunCntList = hikAgvTaskMapper.getTaskRunCnt();
        Map<String,Integer> taskRunCntMap = new HashMap<>();
        for(RoadWayRunCntVo obj : taskRunCntList){
            taskRunCntMap.put(obj.getRoadWayCode(),obj.getRunCnt());
        }
        List<HikAgvRoadWayResult> hikAgvRoadWayResults = this.baseMapper.customList(q);
        for(HikAgvRoadWayResult obj : hikAgvRoadWayResults){
            rsVo = new RoadWayListRsVo();
            rsVo.setRoadWayCode(StringUtils.leftPad(obj.getRoadWayCode(),3,"0")+"巷道");
            rsVo.setAllNum(obj.getAllNum());
            rsVo.setSeq(obj.getSeq());
            rsVo.setPlateNumber(obj.getPlateNumber());
            rsVo.setTrainSeq(obj.getTrainSeq());
            rsVo.setTrainRoadWaySeq(obj.getTrainRoadWaySeq());
            rsVo.setClientId(obj.getClientId());
            rsVo.setClientName(obj.getClientName());
            rsVo.setDockPlat(obj.getDockPlat());
            rsVo.setFlag(obj.getFlag());
            //处理巷道位置 已放托
            Integer seq = Integer.valueOf(rsVo.getSeq());
            rsVo.setHuoCnt(seq);

            //处理巷道位置 已下任务
            Integer roadWayRunCnt = taskRunCntMap.get(obj.getRoadWayCode());
            Integer zhanCnt = 0;
            if(roadWayRunCnt != null){
                zhanCnt = roadWayRunCnt;
                if(rsVo.getAllNum() - seq < roadWayRunCnt){
                    zhanCnt = rsVo.getAllNum() - seq;
                }
            }else{
                roadWayRunCnt = 0;
            }
            rsVo.setZhanCnt(zhanCnt);
            rsVo.setKongCnt(rsVo.getAllNum() - seq - zhanCnt);
            //处理巷道位置 超托
            Integer chao = roadWayRunCnt + seq  - rsVo.getAllNum();
            if(chao < 0){
                chao = 0;
            }
            rsVo.setChaoCnt(chao);
            rsVo.setTrainSeqStr(rsVo.getTrainSeq()+"-"+rsVo.getTrainRoadWaySeq());
            rs.add(rsVo);
        }
        return rs;
    }

    private Serializable getKey(HikAgvRoadWayParam param){
        return param.getRoadWayCode();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private HikAgvRoadWay getOldEntity(HikAgvRoadWayParam param) {
        return this.getById(getKey(param));
    }

    private HikAgvRoadWay getEntity(HikAgvRoadWayParam param) {
        HikAgvRoadWay entity = new HikAgvRoadWay();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
